import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Form, Select, message } from 'antd';
import FormItem from '../../../../../components/FormItem';
import SingleFile from '../../../../../components/Upload/SingleFile';
// import UploadFile from './uploadFile'
import services from '../../../../../services/api';
import storage from '../../../../../utils/storage'
import Tables from './tab'

function Step1(props) {
  const [channelList, setChannelList] = useState([]); // 渠道数据
  const [productList, setProductList] = useState([]); // 产品数据
  const [eventList, setEvents] = useState([]); // 事件
  const [machApp, setMachApp] = useState(true); // 渠道数据
  const [machProduct, setMachProduct] = useState(true); // 产品数据
  const [isDisable, setIsDisable] = useState(false); // 是否禁止下一步
  useEffect(() => {
    getAppCodeList();
    getProductCodeList();
    getEventCodeList();
  }, []);
  useEffect(() => {
    isMatching();
  }, [props.evenData, props.appData,props.productData,channelList,productList,eventList]);
  useEffect(() => {
    if (props.existedEvent) {
      const obj =  props.form.getFieldsValue();
      const newAppObj = channelList.find(it => it.app_id === obj.app_id) || {};
      getNowProductcode({app_name: newAppObj.app_name || props.appData.app_name , event_code: props.evenData.event_code});
      // props.form.setFieldsValue({'product_id': ''});
    }
  }, [props.existedEvent]);
  // 是否有匹配渠道和产品
  function isMatching() {
    const eventsIds = eventList.filter(item => item.event_id === Number(props.evenData.event_id));
    if (!eventsIds.length) { // 事件没有，允许选择渠道产品
      setMachApp(false);
      setMachProduct(false);
      props.form.setFieldsValue({'app_id': '', 'product_id': ''});
      return
    }
    const {appIds, productIds} = setAppAndProcut(Number(props.appData.app_id),  Number(props.productData.product_id));
    Object.keys(appIds).length ? setMachApp(true) : setMachApp(false);
    Object.keys(productIds).length ? setMachProduct(true) : setMachProduct(false);
    if (props.appData.is_modify  || Object.keys(appIds).length) {
      props.form.setFieldsValue({'app_id': Number(props.appData.app_id)})
    } else {
      props.form.setFieldsValue({'app_id': ''})
    }
    if (props.productData.is_modify || Object.keys(productIds).length) {
        props.form.setFieldsValue({'product_id': props.productData.product_id ? Number(props.productData.product_id) : ''});
      } else {
        props.form.setFieldsValue({'product_id': ''});
      }
  };
   //渠道列表请求
  function getAppCodeList ({ product_id = -1, event_id = -1 } = {}) {
    services.application.getAppCodeList({ product_id, event_id }).then((res) => {
      if (res.code === 0) {
        setChannelList(res.data);
      }
    });
  };
  // 事件
  function getEventCodeList({app_id = -1, product_id = -1} = {}) {
    services.event.getEventCodeList({ app_id, product_id}).then((res) => {
      if (res.code === 0) {
        setEvents(res.data) 
      } else {
        message.error(res.msg);
      }
    });
  };
  // 获取当前系统产品
  function getNowProductcode ({ app_name = '', event_code = '' } = {}) {
    services.product.getRelationProduct({ app_name, event_code }).then((res) => {
      if (res.code === 0) {
        props.form.setFieldsValue({'product_id':  res.data.product_id ? Number(res.data.product_id) : ''});
      };
    });
  }; 
  // 产品列表请求
  function getProductCodeList ({ app_id = -1, event_id = -1 } = {}) {
    services.product.getProductCodeList({ app_id, event_id }).then((res) => {
      if (res.code === 0) {
        setProductList(res.data);
      };
    });
  };
  // 上传
  function handleChange(data) {
    const formData = new FormData();
    formData.append('strategy_file', data.file);
    setIsDisable(false);
    if (!data.file) {
      props.setDataFn && props.setDataFn({});
      props.form.setFieldsValue({'product_id': '', 'app_id': ''});
      return
    }
    props.type && services[props.type].uploadFiles(formData).then(res => {
      if (!res.code) {
        props.form.setFieldsValue({'product_id': '', 'app_id': ''});
        props.setDataFn && props.setDataFn(res.data);
      } else {
        setIsDisable(true);
        message.error(res.msg);
      }
    });
  };
  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        props.getRule && props.getRule();
        const {app_id,product_id, strategy_file} = values;
        const params = {
          file_id: props.fileId,
          app_id,
          product_id,
          dept_id: storage.dept,
          conflicts: props.data
        };
        const {appIds, productIds} = setAppAndProcut(app_id,product_id);
        const appAndProcutName = {
          app_name: appIds.app_name || '',
          product_name: productIds.product_name || ''
        }
        const backData = {
          files: strategy_file,
          productIds: productIds,
          appIds: appIds
        };
        props.setBackData(backData); // 回显用
        props.setAppAndProcut(appAndProcutName);
        services[props.type].importConfirm(params).then(res => {
          if (!res.code) {
            props.setSubmitData && props.setSubmitData(res.data);
            props.goto && props.goto();
          } else {
            message.error(res.msg);
          }
        }).catch(err => {
          message.error(err);
        })
      };
    });
  };
  // 获取渠道和产品名称
  function setAppAndProcut(app_id, product_id) {
    const appIds = channelList.find(item => item.app_id === app_id) || {};
    const productIds = productList.find(item => item.product_id === product_id) || {};
    return {
      appIds,
      productIds
    };
  };
  const formItems1 = [
    {
      label: {
        label: '文件上传',
        extra: '格式后缀为.txt的文件'
      },
      name: 'strategy_file',
      options: {
        initialValue: props.files,
        rules: [{ required: true, message: '请选择要导入的文件' }]
      },
      component: <SingleFile onChange={handleChange} isClearFile={true} />
    },
    {
        label: {
          label: '事件名称',
        },
        name: 'strategy_files',
        options: {
          initialValue: '',
        },
        component: (
        <span>{props.evenData.event_name}</span>
        )
      },
    {
      label: {
        label: '选择渠道'
      },
      name: 'app_id',
      options: {
        initialValue: (props.appData.is_modify && (Number(props.appData.app_id) || '')) || ((machApp && Number(props.appData.app_id)) || ''),
        rules: [{ required: true, message: '请选择渠道' }]
      },
      component: (
        <Select
          onChange={(value) => {props.selectApp && props.selectApp(value)}}
        >
          {channelList
            .filter(item => item.app_id !== -1)
            .map(it => {
              return (
                <Select.Option key={it.app_id} value={it.app_id}>
                  {it.app_name}
                </Select.Option>
              );
            })}
        </Select>
      )
    },
    {
        label: {
          label: '选择产品'
        },
        name: 'product_id',
        options: {
          initialValue: (props.productData.is_modify && (Number(props.productData.product_id) || '')) 
          || ((machProduct && Number(props.productData.product_id)) || '')
          || ((!props.existedEvent && Number(props.productData.product_id)) || '')
        },
        component: (
          <Select allowClear disabled={props.existedEvent}>
            {productList
              .filter(item => item.product_id !== -1)
              .map(it => {
                return (
                  <Select.Option key={it.product_id} value={it.product_id}>
                    {it.product_name}
                  </Select.Option>
                );
              })}
          </Select>
        )
      }
  ];
  return (
    <div className='tantuer'>
      <div className='tantuer-form'>
        <Form onSubmit={() => false} className='login-form'>
          <div className='strategy-operater-content'>
            <div style={{ width: '60%', margin: '20px auto 0 auto' }}>
              <Row type='flex' key={1}>
                {formItems1.map(item => {
                  return (
                    <Col span={12} key={item.name}>
                      <FormItem form={props.form} item={item} colNum={1} />
                    </Col>
                  );
                })}
              </Row>
            </div>
            <Tables {...props}/>
            <div className='strategy-operater-ft'>
              <Row type='flex' justify='center' key={2}>
                <Col span={12} style={{ textAlign: 'center' }}>
                  <Button type='primary' onClick={handleSubmit} disabled={props.insideData.length > 0 || isDisable}>
                    下一步
                  </Button>
                </Col>
              </Row>
            </div>
          </div>
        </Form>
      </div>
    </div>
  );
}

export default Form.create()(Step1);
